<?php

namespace App\Console\Commands;

use App\model\WechatUser;
use App\User;
use Illuminate\Console\Command;

class WorkUserCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'workUser:pull';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '拉取部门用户 五分钟同步一次';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //拉取企业用户信息
        $app= \EasyWeChat::work();

        $result=$app->user->getDetailedDepartmentUsers(1,true);
        if ($result['errcode']==0){

            foreach ($result['userlist'] as $item){

                $user=WechatUser::where('userid',$item['userid'])->first();
                if (!$user){
                    $user=new WechatUser();
                }
                $user->email=$item['email'] ?? '';
                if (isset($item['name'])){
                    $user->name=$item['name'];
                }

                if (isset($item['mobile'])){
                    $user->mobile=$item['mobile'];
                }
                if (isset($item['status'])){
                    $user->status=$item['status'];
                }
                /*  if (isset($item['is_leader_in_dept'])){
                      $user->is_leader_in_dept=$item['is_leader_in_dept'];
                  }*/
                $user->userid=$item['userid'];
                $adminUser=User::whereMobile($user->mobile)->orWhere(
                    'realname',$item['name']
                )->first();
                if ($adminUser){
                   $user->admin_user_id=$adminUser->id;
                }
                $user->save();
                $this->info($user->id);
            }
        }
    }
}
